import sys
import string
import types
import os.path
import urllib
from datetime import datetime
import time
from xml.sax import saxexts
from xml.sax import saxlib
from UserStack import UserStack
import dateutilparser
import dateutilrelativedelta
import dateutilrrule
import commands
import os
from dateutilparser import parse

def get_attr_map(attrs):
	attrMap = {}
	for i in range(0, len(attrs)):
		if not attrMap.has_key(attrs.getName(i)):
			attrMap[attrs.getName(i)] = attrs.getValue(i)
	return attrMap

class VerySimpleHandler(saxlib.DocumentHandler):

	def __init__(self):
		self.appt_list = []
		self.path = '/'


	def startElement(self, name, attrs):
		attrMap = get_attr_map(attrs)
		self.path = os.path.join(self.path,name)
 
	def endElement(self, name):
		(self.path, dont_care) = os.path.split(self.path)

   	def characters(self, ch, start, length):
		temp_info = ch[start:start+length]
		if self.path == '/feed/entry/title':
			self.appt_list.append([self.path,temp_info])
		if self.path == '/feed/entry/summary':
			self.appt_list.append([self.path,temp_info])
				
	def returnCal(self):
		self.myAppt = Appointment()
                self.myCal = []
                self.temp_info = ""
		#This will create the calendar and pass it back
		for i in range (0,len(self.appt_list) -1):
			if self.appt_list[i][0] == '/feed/entry/title':
				self.myAppt.addName(self.appt_list[i][1])
                        elif self.appt_list[i][0] == '/feed/entry/summary':
				self.myAppt.addDetails(self.appt_list[i][1])
				self.myCal.append(self.myAppt)
				self.myAppt = Appointment()
			
		return self.myCal
		

		
class Appointment:
   def __init__(self):
        self.appt_desc =''
        self.appt_time = ''
        self.appt_name = ''
	self.appt_place = ""
	self.appt_hr = ''
	self.appt_min = ''

   def addAppt(self,desc,time):
        self.appt_desc = desc
        self.appt_time = time
          
   def addName(self,name):
	self.appt_name = name


   def getName(self):
	self.appt_name


   #This will be used for the voice part
   def getInfo(self):
	if self.appt_hr > 12:
		temp_hr = self.appt_hr - 12
		str_temp = "Appointment at ,%s pm, %s." % (temp_hr,self.appt_name)
	else:
		str_temp = "Appointment at, %s am, %s." % (self.appt_hr,self.appt_name)
	return str_temp
   def addDesc(self,desc):
        self.appt_desc = desc
   
   def getTime(self):
	return self.appt_time


   def getDesc(self):
	return self.appt_desc
   
   def setPlace(self,pl):
	self.appt_place = pl

   def getPlace(self):
	return self.appt_place

   def addDetails(self,str):
	#Adding non-recurring events
	if str.find("When:") > -1:
		stpt = 5
		endpt = str.find("to")
		if endpt > -1:
			self.appt_time = str[stpt:endpt]
		else:
			#Checking for a where to find the end of appt time
			if str.find("Where:") > -1:
				endpt = str.find("Where:")
				self.appt_time = str[stpt:endpt]
				#Adding location
				if str.find("Event Status:") > -1:
					stpt = endpt + 6
					endpt = str.find("Event Status:")
					self.appt_place = str[stpt:endpt]
				
			else:
				#Since no where was found.  Looking for Event Status
				endpt = str.find("Event Status:")
				self.appt_time= str[stpt:endpt]
	temp_dt = parse(self.appt_time)
	self.appt_hr = temp_dt.hour
	self.appt_min = temp_dt.min

#Method to create vxml files once text has been created
def strToFile(text,filename):
	output = file(filename,"w")
	output.write(text)
	output.close()

def createVXML(appt):
	end_str = '''<block>
                Main Menu.
      </block>
      <field name="choice">
         <prompt>
            Please choose from the following:
            To hear your next appointment, say next.
            To hear your current days schedule, say day.
            To exit this program, say good-bye.
         </prompt>
         <grammar>
		last | next | day | good-bye
         </grammar>
         <noinput>
            I didn't hear you.  <reprompt/>
         </noinput>
         <nomatch>
            I didn't quite understand you.  <reprompt/>
         </nomatch>
         <filled>
            <if cond="choice=='last'">
		OK let's hear your last appointment.
                <goto next="prev.vxml"/>
            <elseif cond="choice=='next'"/>
               OK let's hear your next appointment.
                <goto next="next.vxml"/>
            <elseif cond="choice=='day'"/>
               <goto next="day.vxml"/>
            <elseif cond="choice=='good-bye'"/>
                Good-Bye<disconnect/>
            </if>
	</filled>
     </field></form></vxml>'''
	curr_time = datetime.now()
	today_apt= {}
	prev_appt = ''
	next_appt = ''
	temp_str = '<block>'
	for item in appt:
		#Checking if appt is for today
		temp_dt = parse(item.getTime())
		if temp_dt.date()== curr_time.date():
			today_apt[item.getTime()] = item.getInfo()
		if next_appt == '' and temp_dt > curr_time:
			next_appt = item
			

#Creating day.vxml
	#Sorting the dates by time and creating the day calendar
	temp_key = today_apt.keys()
	temp_key.sort()
	for key in temp_key:

		temp_str =  temp_str + today_apt[key] + ',, </block><block>'
	temp_str = temp_str + '</block>'
	contents_header = '''<?xml version="1.0"?><vxml version="2.0" xmlns="http://www.w3.org/2001/vxml">
                      <meta name="maintainer" content="szelisk@lumc.edu"/>
                      <proptery name="bargein" value="false"/>
		   <form id="Choices"> '''
        contents = contents_header + temp_str + end_str 
	
	strToFile(contents,'day.vxml')
#Creating prev.vxml
#	if prev_appt == '':
#		temp_str = "No previous appointments so far today"
#	else:
#		temp_str = "Your previous " + prev_appt.getInfo()
#	contents = '''<?xml version="1.0"?><vxml version="2.0" xmlns="http://www.w3.org/2001/vxml">
#                      <form><block>''' + temp_str +  '''</block></form></vxml>'''
#	contents = contents_header + temp_str + end_str
#	strToFile(contents,'prev.vxml')
#Creating next.vxml
	if next_appt == '':
		temp_str = "No more appointments for today"
	else:
		temp_str = "Your next " + next_appt.getInfo()
	contents = '''<?xml version="1.0"?><vxml version="2.0" xmlns="http://www.w3.org/2001/vxml">
                   <form><block>''' + temp_str + '''</block></form></vxml>'''
	contents = contents_header + temp_str + end_str
	strToFile(contents,'next.vxml')

#Loading the data from Google
def loadData():
	vsh = VerySimpleHandler()
	parser = saxexts.make_parser()
	parser.setDocumentHandler(vsh)
	weburl = "http://www.google.com/calendar/feeds/szelisk@lumc.edu/private-2bf23928da0f61b0c866655fbd9d213e/basic"
	f = urllib.urlopen(weburl)
	infile = f.readlines()
	tempFile = ""
	newFile = ""
	i = 0
	while(i < len(infile)):
		newList = infile[i].split('\n')
		for item in newList:
			tempFile = tempFile + item
		i = i + 1

	tempFile = tempFile.split('&amp;nbsp')
	for item in tempFile:
		newFile = newFile + item
	tempFile = newFile.split('&lt;br&gt;')
	newFile = ''
	for item in tempFile:
		newFile = newFile + item

	#Opening the temp file to write the new xml info to
	myFile = open('tempFile.xml','w')
	myFile.write(newFile)
	myFile.close()
	#Opening the file to give to the parser
	myFile = open('tempFile.xml','r')
	parser.parseFile(myFile)
	myAppt = vsh.returnCal()
	createVXML(myAppt)



loadData()
